package org.momo.rpc.server.impl;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.momo.rpc.protocol.RpcMessage;
import org.momo.rpc.protocol.RpcResponse;
import org.momo.rpc.protocol.codec.NettyDecodeHandler;
import org.momo.rpc.protocol.codec.NettyEncodeHandler;
import org.momo.rpc.server.Server;

import java.util.concurrent.TimeUnit;

@Slf4j
public class NettyServer implements Server {
    private final ServerBootstrap serverBootstrap;

    private final NioEventLoopGroup bossEventLoop;

    private final NioEventLoopGroup workerEventLoop;

    private ChannelFuture cf;

    public NettyServer() {
        bossEventLoop = new NioEventLoopGroup(1);
        workerEventLoop = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());  // CPU逻辑核心数

        serverBootstrap = new ServerBootstrap()
                .group(bossEventLoop, workerEventLoop)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel sc) throws Exception {
                        ChannelPipeline pipeline = sc.pipeline();
                        pipeline.addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
                        pipeline.addLast(new NettyEncodeHandler<RpcMessage<RpcResponse>>());
                        pipeline.addLast(new NettyDecodeHandler());
                        pipeline.addLast(new NettyServerHandler());
                    }
                });
    }


    @Override
    public void start(int port) {
        try {
            cf = serverBootstrap.bind(port).sync();
        } catch (InterruptedException e) {
            log.error("netty server fail to start! the error is {}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @Override
    public void stop() {
        if(cf != null) {
            cf.channel().close();
        }

        if (bossEventLoop != null && !bossEventLoop.isShutdown()) {
            bossEventLoop.shutdownGracefully();
        }

        if (workerEventLoop != null && !workerEventLoop.isShutdown()) {
            workerEventLoop.shutdownGracefully();
        }

        log.info("netty server stop");
    }

}
